import React from 'react'
import '../assets/styles'
import Scrollbars from './CustomScrollbars'
import {connect} from 'react-redux';
import moment from "moment";
import ContextMenu from "./ContextMenu";
import IndexService from "../service/IndexService";
import enums from '../basic/enums'


/**
 * 名称：顶部Tab
 * 创建人：Dada.
 * 创建时间：2021年07月22日15:53:42
 */
class EditorTab extends React.Component {
    indexService = new IndexService();
    //滚动容器Ref
    scrollbarsRef = null;
    //当前选中的tab
    activeTabRef = null;

    constructor(props) {
        super(props);
        this.state = {
            dragMyIndex: -1,
            dragTargetIndex: -1,
            tabList: props.tabList,
        }
    }

    componentDidMount() {

    }

    onTabItemClick = (item, e) => {
        this.props.selectedOpenItem(item)
        e.preventDefault();
    }

    //tab关闭点击事件
    onCloseTabClick(item, index, e) {
        this.props.closeOpenItem(item, index);
        e.stopPropagation();
    }

    onDragStart = (e) => {
        let {index} = e.target.dataset;
        this.setState({
            dragMyIndex: parseInt(index)
        })
    }

    handleDragEnter = (e) => {
        let {dragMyIndex} = this.state;
        let {index} = e.target.dataset;
        index = parseInt(index);
        if (dragMyIndex != index) {
            this.setState({
                dragTargetIndex: index
            })
            e.preventDefault();
        }
    }

    handleDragLeave = (e) => {
        this.setState({
            dragTargetIndex: -1
        })
    }

    handleDrop = (e) => {
        let {dragTargetIndex, dragMyIndex} = this.state;
        this.props.moveIndexForOpenList(dragMyIndex, dragTargetIndex);
        this.setState({
            dragTargetIndex: -1,
            dragMyIndex: -1
        })
    }
    findTabItemById = (id) => {
        let {openList} = this.props;
        for (let item of openList) {
            if (item._id == id) {
                return item;
            }
        }
    }

    onLoadMenuList = () => {
        const {toElement} = event;
        let elem = $(toElement);

        let generalMenuList = []

        if (elem.hasClass('tab-item') || elem.parents('.tab-item').eq(0)[0]) {
            let tabId = elem.data('id');
            let tabIndex = elem.data('index');
            if (!tabId) {
                tabId = elem.parents('.tab-item').data('id');
                tabIndex = elem.data('index');
            }
            generalMenuList = generalMenuList.concat([
                {
                    name: '关闭标签卡',
                    isLine: false,
                    isBan: false,
                    event: (item, e) => {
                        this.props.closeOpenItem(this.findTabItemById(tabId), tabIndex)
                    }
                }, {
                    name: '关闭其他标签卡',
                    isLine: false,
                    isBan: false,
                    event: (item, e) => {
                        let {openList} = this.props;
                        for (let i = openList.length - 1; i >= 0; i--) {
                            if (i !== tabIndex) this.props.closeOpenItem(openList[i], i);
                        }
                    }
                }, {
                    name: '关闭右侧标签卡',
                    isLine: false,
                    isBan: false,
                    event: (item, e) => {
                        let {openList} = this.props;
                        for (let i = openList.length - 1; i >= tabIndex + 1; i--) {
                            this.props.closeOpenItem(openList[i], i);
                        }
                    }
                }, {
                    name: '关闭所有标签卡',
                    isLine: false,
                    isBan: false,
                    event: (item, e) => {
                        let {openList} = this.props;
                        for (let i = openList.length - 1; i >= 0; i--) {
                            this.props.closeOpenItem(openList[i], i);
                        }
                    }
                }, {
                    name: '复制标签卡到分栏',
                    isLine: true,
                    isBan: true,
                    event: (item, e) => {

                    }
                }, {
                    name: '上下2栏',
                    isLine: false,
                    isBan: true,
                    event: (item, e) => {

                    }
                }, {
                    name: '左右2栏',
                    isLine: false,
                    isBan: true,
                    event: (item, e) => {

                    }
                }
            ])
        } else {
            //点在了其他位置
        }
        return generalMenuList
    }

    bindActiveTabRef = (ref, item) => {
        if (item.isActive) {
            this.activeTabRef = ref
        }
    }

    //加号按钮点击事件
    addBtnClick = () => {
        let fileName = moment().format('yyyyMMDDHHmmss-SSS') + '.txt';
        let pid = '';
        //1跟目录新增一个文档
        let node = this.indexService.addItem(pid, fileName, enums.FileType.file, '');
        //2tree新增一个节点
        let treeNode = this.indexService.procItemToZtreeNode(node);
        this.props.zTreeObj.addNodes(null, -1, treeNode);
        treeNode = this.props.zTreeObj.getNodesByParam('_id', treeNode._id);
        this.props.zTreeObj.selectNode(treeNode);
        //3打开这个节点
        this.props.openFile(node);
    }

    render() {
        let {dragTargetIndex} = this.state;
        let {openList} = this.props;
        if (openList.length > 0) {
            setTimeout(() => {
                let warpWidth = this.scrollbarsRef.scrollbar.container.offsetWidth;
                let curLeft = this.scrollbarsRef.scrollbar.view.scrollLeft;
                let toLeft = $('.tab-item.active')[0].offsetLeft;
                if (toLeft > warpWidth || toLeft < curLeft) {
                    this.scrollbarsRef.scrollRight(toLeft - (toLeft != 0 ? 100 : 0));
                }
            }, 0)
        }
        return (
            <ContextMenu className={'tab-menu-warp'} onLoadMenuList={this.onLoadMenuList}>
                <Scrollbars className='tab-warp' style={{height: '30px'}} ref={ref => this.scrollbarsRef = ref}>
                    {openList.map((item, index) => {
                        return (
                            <div
                                draggable={true}
                                onDragStart={this.onDragStart}
                                onDragEnter={this.handleDragEnter}
                                onDragLeave={this.handleDragLeave}
                                onDragOver={this.handleDragEnter}
                                onDrop={this.handleDrop}
                                data-id={item._id}
                                data-index={index}
                                key={item._id}
                                onClick={this.onTabItemClick.bind(this, item)}
                                className={`tab-item ${item.isActive ? 'active' : ''} ${dragTargetIndex == index ? 'dragIn' : ''} `}>
                                {item.name}
                                <em className='btn iconfont icon-x'
                                    onClick={this.onCloseTabClick.bind(this, item, index)}>
                                </em>
                            </div>
                        )
                    })}
                </Scrollbars>
                <div className='add-btn-warp' onClick={this.addBtnClick}>
                    <em className='btn iconfont icon-jia'></em>
                </div>
            </ContextMenu>
        );
    }
}

export default connect((state, p) => {
    return {...state}
}, (dispatch) => {
    return {
        openFile(item) {
            dispatch({
                type: 'openFile',
                data: item
            })
        },
        closeOpenItem(item, index) {
            dispatch({
                type: 'closeOpenItem',
                data: {item, index}
            })
        }, selectedOpenItem(item) {
            dispatch({
                type: 'selectedOpenItem',
                data: item
            })
        }, moveIndexForOpenList(dragMyIndex, dragTargetIndex) {
            dispatch({
                type: 'moveIndexForOpenList',
                data: {dragMyIndex, dragTargetIndex}
            })
        }
    }
})(EditorTab);
